import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/home/controllers/home_controller.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../controllers/scene_controller.dart';

class SceneView extends GetView<SceneController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: _appBar,
      body: Stack(
        children: [
          Image.asset(
            Assets.imagesListBack,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
          Container(
            width: double.infinity,
            child: SafeArea(
              child: Container(
                padding: EdgeInsets.only(left: 12, right: 12, top: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      LocaleKeys.scene_max_num.tr,
                      style: MFont.regular13.apply(color: Colors.white),
                      textAlign: TextAlign.start,
                    ),
                    SizedBox(height: 16),
                    Expanded(
                      child: Obx(() {
                        final dataList = controller.sceneList.value;
                        return SmartRefresher(
                          controller: controller.refreshController,
                          onRefresh: () => controller.fetchSceneList(),
                          child: ListView.builder(
                            itemCount: dataList.length + 1,
                            itemBuilder: (ctx, index) {
                              return index == dataList.length ? _addView : _sceneView(index);
                            },
                          ),
                        );
                      }),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  get _appBar {
    return AppBar(
      backgroundColor: Colors.transparent,
      systemOverlayStyle: SystemUiOverlayStyle.light,
      actions: [menuItem],
    );
  }

  get menuItem {
    Widget _itemAction(String title, int index) {
      return CupertinoActionSheetAction(
        child: Text(
          title,
          style: MFont.semi_Bold15.apply(color: MColor.xFF000000),
        ),
        isDefaultAction: index == 3 ? true : false,
        onPressed: (() {
          Get.back();
          if (index == 0) {
            Get.toNamed(Routes.ADD_DEVICE)?.then((value) {
              BlueService.share.isAll = false;
              Get.find<HomeController>().refreshAction();
            });
          } else if (index == 1) {
            Get.toNamed(
              Routes.DEVICE_MANAGER,
              arguments: {
                'group': true,
                'add': true,
                'name': LocaleKeys.add_devices_group_title.tr,
              },
            )?.then((value) => Get.find<HomeController>().refreshAction());
          } else if (index == 2) {
            Get.toNamed(Routes.SCENE_DETAIL)?.then((value) {
              controller.fetchSceneList();
            });
          }
        }),
      );
    }

    return GestureDetector(
      onTap: () {
        showCupertinoModalPopup(
            context: Get.context!,
            builder: (ctx) {
              return CupertinoActionSheet(
                actions: [
                  _itemAction(LocaleKeys.home_add_device.tr, 0),
                  _itemAction(LocaleKeys.home_create_group.tr, 1),
                  _itemAction(LocaleKeys.home_create_scene.tr, 2),
                ],
                cancelButton: _itemAction(LocaleKeys.devices_cancel.tr, 3),
              );
            });
      },
      child: Container(
        padding: EdgeInsets.only(right: 12),
        child: Image.asset(Assets.imagesInsertIcon, width: 30, height: 30),
      ),
    );
  }

  Widget _sceneView(int index) {
    final scene = controller.sceneList[index];
    DateFormat format = DateFormat("MM-dd-yyyy HH:mm:ss");

    final startTime = format.parse(scene.startTime ?? '');
    final endTime = format.parse(scene.endTime ?? '');

    final startStr = formatDate(startTime, [mm, '-', dd]);
    final endStr = formatDate(endTime, [mm, '-', dd]);

    return Obx(() {
      final isLock = scene.lockState.value;
      final turn = scene.turnState.value;

      return GestureDetector(
        onTap: () {
          controller.toDetail(index);
        },
        onLongPress: () {
          controller.deleteConfirm(scene.sceneId!);
        },
        child: Container(
          margin: EdgeInsets.only(bottom: 16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
          ),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withAlpha(30),
                  blurRadius: 3,
                  offset: Offset(0, 2),
                  spreadRadius: 1,
                )
              ],
              image: DecorationImage(image: AssetImage(Assets.imagesSceneBack), fit: BoxFit.fill),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            scene.sceneName ?? '-',
                            style: MFont.semi_Bold20.apply(color: MColor.xFF333333),
                          ),
                          Row(
                            children: [
                              Text(
                                startStr,
                                style: MFont.regular15.apply(color: MColor.xFF999999),
                              ),
                              SizedBox(width: 8),
                              Icon(
                                Icons.arrow_forward,
                                size: 20,
                                color: MColor.xFFCCCCCC,
                              ),
                              SizedBox(width: 8),
                              Text(
                                endStr,
                                style: MFont.regular15.apply(color: MColor.xFF999999),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: () => controller.fetchTurnScene(index),
                      child: Image.asset(
                        turn ? Assets.imagesSceneOpen : Assets.imagesSceneClose,
                        width: 47,
                        height: 24,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 24),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () => controller.fetchLockScene(index),
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(13),
                          color: isLock ? MColor.skin : MColor.xFFEEEEEE,
                        ),
                        padding: EdgeInsets.only(right: 12),
                        child: Row(
                          children: [
                            Image.asset(
                              isLock ? Assets.imagesSceneLock : Assets.imagesSceneUnlock,
                              width: 28,
                              height: 28,
                            ),
                            Text(
                              isLock ? LocaleKeys.scene_locked.tr : LocaleKeys.scene_unlock.tr,
                              style: isLock
                                  ? MFont.regular13.apply(color: Colors.white)
                                  : MFont.regular13.apply(color: MColor.xFF999999),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Spacer(),
                    Row(
                      children: [
                        Text(
                          LocaleKeys.scene_setting.tr,
                          style: MFont.regular13.apply(color: MColor.skin),
                        ),
                        SizedBox(width: 3),
                        Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: 15,
                          color: MColor.skin,
                        ),
                      ],
                    )
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  get _addView {
    return Container(
      width: double.infinity,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          Get.toNamed(Routes.SCENE_DETAIL)?.then((value) {
            controller.fetchSceneList();
          });
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 32),
          child: Center(
            child: Container(
              width: 64,
              height: 64,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(32),
              ),
              child: Center(child: Image.asset(Assets.imagesListInsert, width: 32, height: 32)),
            ),
          ),
        ),
      ),
    );
  }
}
